﻿using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace LightCAD.UI
{
    public partial class TitleTabControl : UserControl, ITitleTabBar
    {
  
        public static Image DefaultIcon = Properties.FileTypeResources.file_dwg24;
        // public static Image DefaultIcon = Properties.Resources.Homepage;
        public static string DefaultText = "Drawing";
        public event EventHandler AddTabClick;
        public event EventHandler CloseTabClick;
        public event EventHandler SelectTabClick;
        private List<TitleTabItem> tabs = new List<TitleTabItem>();
        public TitleTabControl()
        {
            InitializeComponent();
            this.picAdd.Click += PicAdd_Click;
            this.picAdd.MouseEnter += PicAdd_MouseEnter;
            this.picAdd.MouseLeave += PicAdd_MouseLeave;
        }

        public void ApplyTheme(ThemeMode themeMode)
        {
            if(themeMode ==  ThemeMode.Dark)
            {
                
            }
        }

        public string NewDrawingText()
        {
            var maxNum = 0;
            foreach (TitleTabItemControl tabCtrl in this.pnlTabs.Controls)
            {
                var text = tabCtrl.TabItem.Text;
                if (text.StartsWith(DefaultText))
                {
                    var str = text.Substring(DefaultText.Length);
                    if (int.TryParse(str, out int num))
                    {
                        maxNum = Math.Max(num, maxNum);
                    }
                }
            }
            return DefaultText + (maxNum + 1);
        }
        private void PicAdd_Click(object? sender, EventArgs e)
        {
            var text = NewDrawingText();
            var tabItem = new TitleTabItem
            {
                Icon = DefaultIcon,
                Name = text,
                Text = text,
                Closable = true,
            };
            var tabCtrl = this.AddTab(tabItem);
            if (AddTabClick != null)
            {
                AddTabClick.Invoke(this, new TitleTabEventArgs
                {
                    Type = "Add",
                    TabItem = tabItem,
                    TabItemControl = tabCtrl,
                });
            }
        }

        private void PicAdd_MouseLeave(object? sender, EventArgs e)
        {
            this.picAdd.Image = Properties.TabResources.Add;
        }

        private void PicAdd_MouseEnter(object? sender, EventArgs e)
        {
            this.picAdd.Image = Properties.TabResources.AddHover;
        }

        [Browsable(false)]
        public ReadOnlyCollection<TitleTabItem> Tabs
        {
            get { return new ReadOnlyCollection<TitleTabItem>(Tabs); }
        }

        private void ResetDivider()
        {
            for (var i = 0; i < this.pnlTabs.Controls.Count; i++)
            {
                var tabCtrl = this.pnlTabs.Controls[i] as TitleTabItemControl;
                if (tabCtrl.IsSelected)
                {
                    //由于DockLeft 视觉位置 和对象位置是相反的。
                    //选中的元素及视觉位置前一个元素 无分隔符
                    if (tabCtrl.HasRightDivider != false)
                    {
                        tabCtrl.HasRightDivider = false;
                        tabCtrl.ResetItem();
                    }
                    if (i + 1 < this.pnlTabs.Controls.Count)
                    {
                        var preCtrl = (this.pnlTabs.Controls[i + 1] as TitleTabItemControl);
                        if (preCtrl.HasRightDivider != false)
                        {
                            preCtrl.HasRightDivider = false;
                            preCtrl.ResetItem();
                        }
                        i++;
                    }
                }
                else
                {
                    if (tabCtrl.HasRightDivider != true)
                    {
                        tabCtrl.HasRightDivider = true;
                        tabCtrl.ResetItem();
                    }
                }
            }
        }
        public TitleTabItemControl GetSelectedTabItemControl()
        {
            foreach (TitleTabItemControl tabCtrl in this.pnlTabs.Controls)
            {
                if (tabCtrl.IsSelected)
                {
                    return tabCtrl;
                }
            }

            return null;
        }
        public TitleTabItemControl GetTabItemControl(TitleTabItem tabItem)
        {
            foreach (TitleTabItemControl tabCtrl in this.pnlTabs.Controls)
            {
                if (tabCtrl.TabItem == tabItem)
                {
                    return tabCtrl;
                }
            }
            return null;
        }

        public TitleTabItemControl SelectTab(TitleTabItem tabItem)
        {
            TitleTabItemControl selectedCtrl = null;
            foreach (TitleTabItemControl tabCtrl in this.pnlTabs.Controls)
            {
                if (tabCtrl.TabItem == tabItem)
                {
                    tabCtrl.IsSelected = true;
                    selectedCtrl = tabCtrl;
                }
                else
                    tabCtrl.IsSelected = false;
            }
            ResetDivider();
            return selectedCtrl;
        }
        public TitleTabItemControl AddTab(TitleTabItem tabItem)
        {
            this.tabs.Add(tabItem);
            var tabCtrl = new TitleTabItemControl(tabItem);
            tabCtrl.Dock = DockStyle.Left;
            tabCtrl.AutoSize = true;
            tabCtrl.Width = 0;

            tabCtrl.ItemClick += TabCtrl_ItemClick;
            tabCtrl.ItemClose += TabCtrl_ItemClose;
            this.pnlTabs.Controls.Add(tabCtrl);
            tabCtrl.BringToFront();

            SelectTab(tabItem);
            this.ResetDivider();
            this.Invalidate();

            return tabCtrl;
        }

        private void TabCtrl_ItemClose(object? sender, EventArgs e)
        {
            var tabCtrl = sender as TitleTabItemControl;
            var args = new TitleTabEventArgs
            {
                Type = "Close",
                TabItem = tabCtrl.TabItem,
                TabItemControl = tabCtrl
            };
            CloseTabClick?.Invoke(this, args);
            if (args.IsCancel) return;

            this.RemoveTab(tabCtrl.TabItem);
        }

        private void TabCtrl_ItemClick(object? sender, EventArgs e)
        {
            var tabCtrl = sender as TitleTabItemControl;
            var args = new TitleTabEventArgs
            {
                Type = "Select",
                TabItem = tabCtrl.TabItem,
                TabItemControl = tabCtrl
            };
            SelectTabClick?.Invoke(this, args);
            if (args.IsCancel) return;

            SelectTab(tabCtrl.TabItem);
        }

        public void RemoveTab(TitleTabItem tabItem)
        {
            this.tabs.Remove(tabItem);
            TitleTabItemControl matchedTabCtrl = null;
            for(var i=0;i< this.pnlTabs.Controls.Count;i++)
            {
                var tabCtrl = this.pnlTabs.Controls[i] as TitleTabItemControl;
                if (tabCtrl.TabItem == tabItem)
                {
                    matchedTabCtrl = tabCtrl;
                    //将前一个选中，如果没有，将后一个选中（都是视觉序）
                    if(i+1< this.pnlTabs.Controls.Count)
                    {
                        var newSel = this.pnlTabs.Controls[i + 1] as TitleTabItemControl;
                        //模拟点击，需要触发事件
                        TabCtrl_ItemClick(newSel, EventArgs.Empty);
                    }
                    else if(i-1>=0)
                    {
                        var newSel = this.pnlTabs.Controls[i -1] as TitleTabItemControl;
                        TabCtrl_ItemClick(newSel, EventArgs.Empty);
                    }
                    break;
                }
            }
            if (matchedTabCtrl != null)
            {
                this.pnlTabs.Controls.Remove(matchedTabCtrl);
            }
            
            this.ResetDivider();
            this.Invalidate();
        }

        public void ClearTabs()
        {
            this.tabs.Clear();
            foreach (TitleTabItemControl tabCtrl in this.pnlTabs.Controls)
            {
                tabCtrl.Dispose();
            }
            this.pnlTabs.Controls.Clear();
        }
    }

 
}
